package com.ljkj.zjf.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ljkj.access.Tright;
import com.ljkj.access.Tuserrightrelation;
import com.ljkj.common.db.dao.TUserRightRelationDAO;
import com.ljkj.common.db.dao.TrightDAO;
import com.ljkj.zjf.common.GlobalNames;

public class TuserRightService {
	
	private static Logger logger = LoggerFactory.getLogger(TuserRightService.class);
	private TrightDAO trightDAO;
	private TUserRightRelationDAO tUserRightRelationDAO;
	
	/**
	 * 根据用户ID获取权限。（用户权限关联表）
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public String getUserRightByUserID(Integer userId) throws Exception{
	    
		Map<String, Object> errorMap = new HashMap<String, Object>();
		errorMap.put("errCode", GlobalNames.CALL_RESULT_FAIL);
		
		List<Tuserrightrelation> tuserrightrelations = this.tUserRightRelationDAO.findByProperty("tuId", userId);
		if(tuserrightrelations == null || tuserrightrelations.size() == 0){
			errorMap.put("errMsg", "您尚未分配权限，请联系管理员");
			return JSON.toJSONString(errorMap);
		}else{
			List<Map> maps = new ArrayList<Map>();
			for(Tuserrightrelation tuserrightrelation : tuserrightrelations){
				Tright tright = this.trightDAO.findById(tuserrightrelation.getTrId());
				if(tright.getDisabledState() == 1){
					continue;
				}
				Map<String,String> map = new HashMap<String, String>();
				map.put("id", String.valueOf(tright.getTrId()));
				map.put("text", tright.getRightName());
				if(tright.getParentTrId() != null){
					map.put("pid",String.valueOf(tright.getParentTrId()));
				}
				if(tright.getTrUrl() != null && !"".equals(tright.getTrUrl())){
					map.put("url", tright.getTrUrl());
				}
				maps.add(map);
			}
			return JSON.toJSONString(maps);
		}
	}
	
	public Boolean deleteUserRightRelationByUserId(Integer userId){
		
		List<Tuserrightrelation> tuserrightrelations = this.tUserRightRelationDAO.findByProperty("tuId", userId);
		if(tuserrightrelations != null && tuserrightrelations.size()>0){
			this.tUserRightRelationDAO.delete(tuserrightrelations);
		}
		
		return true;
	}
	
	public Boolean saveUserRightRelation(List<Tuserrightrelation> tuserrightrelations){
		
		try{
			this.tUserRightRelationDAO.save(tuserrightrelations);
			return true;
		}catch(Exception ex){
			ex.printStackTrace();
			return false;
		}
		
	}


	
	//注入DAO
	public void setTrightDAO(TrightDAO trightDAO) {
		this.trightDAO = trightDAO;
	}
	public void settUserRightRelationDAO(TUserRightRelationDAO tUserRightRelationDAO) {
		this.tUserRightRelationDAO = tUserRightRelationDAO;
	}
}
